Popular Searches
Popular Course Categories
Popular Courses

Modify Web Elements

JavaScript with Selenium

<div class="selenium-notes">

<h1>Modify Web Elements in Selenium WebDriver</h1>

<p>Modifying Web Elements in Selenium WebDriver means changing, updating, inspecting, or controlling the properties, attributes, values, styles, text, or state of HTML elements during automated testing. Selenium provides the WebElement interface for normal interaction with elements, while JavaScriptExecutor can be used when direct DOM-level modification is required.</p>

<p>Web Element modification is useful when working with dynamic web applications, debugging automation scripts, changing test data in controlled environments, inspecting element properties, modifying CSS for debugging, working with hidden or disabled states during specialized testing, and validating how the DOM behaves after a change.</p>

<p>Selenium WebDriver training commonly covers locating elements, WebDriver commands, forms, buttons, dropdowns, navigation, and working with WebElements as part of browser automation.</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is a Web Element?</h2>

<p>A Web Element is an HTML element displayed or represented in the browser DOM. Examples include text fields, buttons, links, checkboxes, radio buttons, dropdowns, images, labels, tables, forms, and containers.</p>

<pre><code>&lt;input id="username" type="text" name="username"&gt;

&lt;button id="login"&gt;Login&lt;/button&gt;

&lt;a href="/home"&gt;Home&lt;/a&gt;</code></pre>

<h2>2. What Does Modify Web Elements Mean?</h2>

<p>Modify Web Elements means changing some part of an existing HTML element or its current DOM state during test execution.</p>

<ul>

<li>Change an input value</li>

<li>Change an HTML attribute</li>

<li>Add or remove a CSS class</li>

<li>Change CSS properties</li>

<li>Change element text</li>

<li>Change visibility</li>

<li>Change checkbox or radio state</li>

<li>Add or remove attributes</li>

<li>Modify image properties</li>

<li>Modify links</li>

<li>Modify form controls</li>

<li>Highlight elements for debugging</li>

</ul>

<h2>3. Why Modify Web Elements?</h2>

<p>Element modification is useful in specialized automation and debugging scenarios. It can help testers inspect the DOM, prepare controlled test states, visualize elements, and investigate application behavior.</p>

<ul>

<li>Debug difficult UI problems</li>

<li>Inspect dynamic elements</li>

<li>Highlight elements</li>

<li>Modify test data</li>

<li>Change temporary CSS</li>

<li>Test specific DOM states</li>

<li>Inspect attributes</li>

<li>Investigate hidden elements</li>

<li>Validate dynamic application behavior</li>

</ul>

<h2>4. Selenium WebElement and JavaScriptExecutor</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Technique</th><th>Purpose</th><th>Example</th></tr>

<tr><td>WebElement</td><td>Normal element interaction</td><td>click(), sendKeys()</td></tr>

<tr><td>getAttribute()</td><td>Read attribute/property</td><td>getAttribute("value")</td></tr>

<tr><td>Actions</td><td>Advanced mouse and keyboard actions</td><td>moveToElement()</td></tr>

<tr><td>JavascriptExecutor</td><td>Execute JavaScript in browser</td><td>setAttribute()</td></tr>

<tr><td>CSS modification</td><td>Change visual properties</td><td>style.outline</td></tr>

</table>

<h2>5. Basic Selenium Setup</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;</code></pre>

<h2>6. Starting WebDriver</h2>

<pre><code>WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://example.com");</code></pre>

<h2>7. Locating a Web Element</h2>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));</code></pre>

<h2>8. Common Selenium Locators</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Locator</th><th>Example</th></tr>

<tr><td>ID</td><td>By.id("username")</td></tr>

<tr><td>Name</td><td>By.name("username")</td></tr>

<tr><td>Class Name</td><td>By.className("input-field")</td></tr>

<tr><td>Tag Name</td><td>By.tagName("input")</td></tr>

<tr><td>Link Text</td><td>By.linkText("Login")</td></tr>

<tr><td>Partial Link Text</td><td>By.partialLinkText("Log")</td></tr>

<tr><td>CSS Selector</td><td>By.cssSelector("#username")</td></tr>

<tr><td>XPath</td><td>By.xpath("//input[@id='username']")</td></tr>

</table>

<h2>9. Modifying an Input with sendKeys()</h2>

<p>For normal user-like text entry, Selenium's sendKeys() method should generally be preferred.</p>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");</code></pre>

<h2>10. Clearing an Input</h2>

<pre><code>username.clear();

username.sendKeys("newUser");</code></pre>

<h2>11. Modifying Input Value with JavaScript</h2>

<pre><code>JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].value='admin';",

    username

);</code></pre>

<h2>12. Understanding arguments[0]</h2>

<p>arguments[0] represents the first object passed to executeScript(). When a WebElement is passed to JavaScript, Selenium exposes it to the script as the corresponding DOM element.</p>

<pre><code>js.executeScript(

    "arguments[0].value='admin';",

    username

);</code></pre>

<h2>13. Modifying Multiple Elements</h2>

<pre><code>WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement lastName =

    driver.findElement(By.id("lastName"));

 

js.executeScript(

    "arguments[0].value='John';" +

    "arguments[1].value='Smith';",

    firstName,

    lastName

);</code></pre>

<h2>14. Modifying an HTML Attribute</h2>

<p>The JavaScript setAttribute() method can change an HTML attribute.</p>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('value','admin');",

    username

);</code></pre>

<h2>15. Changing the ID Attribute</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('id','newUsername');",

    username

);</code></pre>

<p>Changing an element's locator attributes during a test can make subsequent automation difficult to maintain, so this technique should normally be restricted to controlled scenarios.</p>

<h2>16. Changing the Class Attribute</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('class','modified-input');",

    username

);</code></pre>

<h2>17. Adding a CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.add('selenium-highlight');",

    username

);</code></pre>

<h2>18. Removing a CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.remove('selenium-highlight');",

    username

);</code></pre>

<h2>19. Toggling a CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.toggle('active');",

    username

);</code></pre>

<h2>20. Checking Whether a Class Exists</h2>

<pre><code>Boolean result = (Boolean) js.executeScript(

    "return arguments[0].classList.contains('active');",

    username

);

 

System.out.println("Class exists: " + result);</code></pre>

<h2>21. Modifying CSS Properties</h2>

<p>JavaScript can modify inline CSS properties through the element's style object.</p>

<pre><code>js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    username

);</code></pre>

<h2>22. Changing Text Color</h2>

<pre><code>js.executeScript(

    "arguments[0].style.color='red';",

    username

);</code></pre>

<h2>23. Changing Background Color</h2>

<pre><code>js.executeScript(

    "arguments[0].style.backgroundColor='lightblue';",

    username

);</code></pre>

<h2>24. Changing Font Size</h2>

<pre><code>js.executeScript(

    "arguments[0].style.fontSize='20px';",

    username

);</code></pre>

<h2>25. Changing Font Weight</h2>

<pre><code>js.executeScript(

    "arguments[0].style.fontWeight='bold';",

    username

);</code></pre>

<h2>26. Changing Border</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='3px solid red';",

    username

);</code></pre>

<h2>27. Changing Outline</h2>

<p>Outline is particularly useful for temporary visual debugging because it generally does not affect the element's layout.</p>

<pre><code>js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    username

);</code></pre>

<h2>28. Adding Box Shadow</h2>

<pre><code>js.executeScript(

    "arguments[0].style.boxShadow='0 0 10px red';",

    username

);</code></pre>

<h2>29. Changing Width</h2>

<pre><code>js.executeScript(

    "arguments[0].style.width='300px';",

    username

);</code></pre>

<h2>30. Changing Height</h2>

<pre><code>js.executeScript(

    "arguments[0].style.height='50px';",

    username

);</code></pre>

<h2>31. Changing Visibility</h2>

<pre><code>js.executeScript(

    "arguments[0].style.visibility='visible';",

    username

);</code></pre>

<h2>32. Hiding an Element</h2>

<pre><code>js.executeScript(

    "arguments[0].style.display='none';",

    username

);</code></pre>

<h2>33. Showing a Hidden Element</h2>

<pre><code>js.executeScript(

    "arguments[0].style.display='block';",

    username

);</code></pre>

<p>Changing visibility through JavaScript is useful for controlled investigation, but it does not necessarily represent how a real user would normally reach or interact with that element.</p>

<h2>34. Removing the Disabled Attribute</h2>

<pre><code>WebElement button =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    button

);</code></pre>

<h2>35. Adding the Disabled Attribute</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('disabled','true');",

    button

);</code></pre>

<h2>36. Reading Attributes Before Modification</h2>

<pre><code>String value =

    username.getAttribute("value");

 

System.out.println(value);</code></pre>

<h2>37. Reading Class Attribute</h2>

<pre><code>String className =

    username.getAttribute("class");

 

System.out.println(className);</code></pre>

<h2>38. Reading ID Attribute</h2>

<pre><code>String id =

    username.getAttribute("id");

 

System.out.println(id);</code></pre>

<h2>39. Reading href Attribute</h2>

<pre><code>WebElement link =

    driver.findElement(By.tagName("a"));

 

String href =

    link.getAttribute("href");

 

System.out.println(href);</code></pre>

<h2>40. Modifying a Link href</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute(" +

    "'href','https://example.com/profile');",

    link

);</code></pre>

<h2>41. Modifying Button Text</h2>

<pre><code>js.executeScript(

    "arguments[0].textContent='Submit Order';",

    button

);</code></pre>

<h2>42. Using innerText</h2>

<pre><code>js.executeScript(

    "arguments[0].innerText='Submit Order';",

    button

);</code></pre>

<h2>43. textContent vs innerText</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Property</th><th>Description</th></tr>

<tr><td>textContent</td><td>Works with the text content of the DOM.</td></tr>

<tr><td>innerText</td><td>Represents rendered text and is influenced by CSS visibility.</td></tr>

</table>

<h2>44. Modifying Placeholder</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute(" +

    "'placeholder','Enter Username');",

    username

);</code></pre>

<h2>45. Removing Placeholder</h2>

<pre><code>js.executeScript(

    "arguments[0].removeAttribute('placeholder');",

    username

);</code></pre>

<h2>46. Modifying the name Attribute</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('name','userName');",

    username

);</code></pre>

<h2>47. Modifying the type Attribute</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('type','text');",

    username

);</code></pre>

<h2>48. Changing Password Input Type</h2>

<pre><code>WebElement password =

    driver.findElement(By.id("password"));

 

js.executeScript(

    "arguments[0].setAttribute('type','text');",

    password

);</code></pre>

<p>This can expose password text visually and should only be used in a controlled test or debugging environment.</p>

<h2>49. Attribute vs Property</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Attribute</th><th>Property</th></tr>

<tr><td>Part of HTML markup</td><td>Current state of the DOM object</td></tr>

<tr><td>Can be modified with setAttribute()</td><td>Can be modified directly with JavaScript</td></tr>

<tr><td>Example: value attribute</td><td>Example: input.value</td></tr>

</table>

<h2>50. Modifying the value Property</h2>

<pre><code>js.executeScript(

    "arguments[0].value='Test Data';",

    username

);</code></pre>

<h2>51. Modifying Checkbox State</h2>

<pre><code>WebElement checkbox =

    driver.findElement(By.id("terms"));

 

js.executeScript(

    "arguments[0].checked=true;",

    checkbox

);</code></pre>

<h2>52. Unchecking a Checkbox</h2>

<pre><code>js.executeScript(

    "arguments[0].checked=false;",

    checkbox

);</code></pre>

<h2>53. Checking Checkbox State</h2>

<pre><code>Boolean checked = (Boolean) js.executeScript(

    "return arguments[0].checked;",

    checkbox

);

 

System.out.println("Checked: " + checked);</code></pre>

<h2>54. Modifying Radio Button State</h2>

<pre><code>WebElement radio =

    driver.findElement(By.id("male"));

 

js.executeScript(

    "arguments[0].checked=true;",

    radio

);</code></pre>

<h2>55. Modifying a Select Element</h2>

<p>For standard HTML select elements, Selenium's Select class should generally be preferred for normal user-like automation.</p>

<pre><code>import org.openqa.selenium.support.ui.Select;

 

WebElement country =

    driver.findElement(By.id("country"));

 

Select select =

    new Select(country);

 

select.selectByVisibleText("India");</code></pre>

<h2>56. JavaScript Modification of Select Value</h2>

<pre><code>js.executeScript(

    "arguments[0].value='IN';",

    country

);</code></pre>

<h2>57. Dispatching a Change Event</h2>

<p>Some applications listen for change events. Changing a DOM property alone may not trigger the application's event handlers.</p>

<pre><code>js.executeScript(

    "arguments[0].value='IN';" +

    "arguments[0].dispatchEvent(" +

    "new Event('change',{bubbles:true})" +

    ");",

    country

);</code></pre>

<h2>58. Dispatching an Input Event</h2>

<pre><code>js.executeScript(

    "arguments[0].value='admin';" +

    "arguments[0].dispatchEvent(" +

    "new Event('input',{bubbles:true})" +

    ");",

    username

);</code></pre>

<h2>59. Why Events Matter</h2>

<p>Modern applications may use JavaScript frameworks that listen for input, change, click, keyboard, or other browser events. Directly changing a DOM property does not always reproduce the complete sequence of events produced by a real user.</p>

<h2>60. Modifying a Textarea</h2>

<pre><code>WebElement message =

    driver.findElement(By.id("message"));

 

js.executeScript(

    "arguments[0].value='Hello Selenium';",

    message

);</code></pre>

<h2>61. Modifying Email Input</h2>

<pre><code>WebElement email =

    driver.findElement(By.id("email"));

 

email.clear();

email.sendKeys("[email protected]");</code></pre>

<h2>62. Modifying an Image</h2>

<pre><code>WebElement image =

    driver.findElement(By.id("productImage"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'src','/images/test.png');",

    image

);</code></pre>

<h2>63. Modifying Image Size</h2>

<pre><code>js.executeScript(

    "arguments[0].style.width='200px';" +

    "arguments[0].style.height='200px';",

    image

);</code></pre>

<h2>64. Modifying Table Rows</h2>

<pre><code>WebElement row =

    driver.findElement(

        By.cssSelector("table tbody tr")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    row

);</code></pre>

<h2>65. Modifying Table Cells</h2>

<pre><code>WebElement cell =

    driver.findElement(

        By.cssSelector("table tbody tr td")

    );

 

js.executeScript(

    "arguments[0].style.fontWeight='bold';",

    cell

);</code></pre>

<h2>66. Modifying Multiple Web Elements</h2>

<pre><code>List&lt;WebElement&gt; elements =

    driver.findElements(

        By.cssSelector(".product")

    );

 

for (WebElement element : elements) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        element

    );

}</code></pre>

<h2>67. Modifying Elements Using CSS Selector</h2>

<pre><code>WebElement element =

    driver.findElement(

        By.cssSelector(".login-button")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);</code></pre>

<h2>68. Modifying Elements Using XPath</h2>

<pre><code>WebElement element =

    driver.findElement(

        By.xpath("//button[text()='Login']")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);</code></pre>

<h2>69. Highlighting a Web Element</h2>

<p>Highlighting is one of the most useful DOM modifications for debugging automation.</p>

<pre><code>js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    element

);</code></pre>

<h2>70. Creating a Highlight Utility</h2>

<pre><code>public static void highlight(

        WebDriver driver,

        WebElement element) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        element

    );

}</code></pre>

<h2>71. Modifying an Attribute with a Utility Method</h2>

<pre><code>public static void setAttribute(

        WebDriver driver,

        WebElement element,

        String attribute,

        String value) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].setAttribute(" +

        "arguments[1], arguments[2]);",

        element,

        attribute,

        value

    );

}</code></pre>

<h2>72. Using the Attribute Utility</h2>

<pre><code>setAttribute(

    driver,

    username,

    "placeholder",

    "Enter Username"

);</code></pre>

<h2>73. Removing an Attribute with a Utility</h2>

<pre><code>public static void removeAttribute(

        WebDriver driver,

        WebElement element,

        String attribute) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].removeAttribute(arguments[1]);",

        element,

        attribute

    );

}</code></pre>

<h2>74. Setting a CSS Property with a Utility</h2>

<pre><code>public static void setStyle(

        WebDriver driver,

        WebElement element,

        String property,

        String value) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style[arguments[1]]=arguments[2];",

        element,

        property,

        value

    );

}</code></pre>

<h2>75. Using the CSS Utility</h2>

<pre><code>setStyle(

    driver,

    username,

    "backgroundColor",

    "yellow"

);</code></pre>

<h2>76. Restoring Original Style</h2>

<pre><code>String originalStyle =

    element.getAttribute("style");

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

 

// Debugging or screenshot operation

 

js.executeScript(

    "arguments[0].setAttribute('style', arguments[1]);",

    element,

    originalStyle

);</code></pre>

<h2>77. Modifying an Element Before Screenshot</h2>

<pre><code>js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    element

);

 

File screenshot =

    ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);</code></pre>

<h2>78. Modify Web Element After Explicit Wait</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("username")

        )

    );

 

highlight(driver, element);</code></pre>

<h2>79. Modifying Dynamic Web Elements</h2>

<p>Dynamic elements may appear after page loading or may be re-rendered by the application. Always synchronize before interacting with them.</p>

<pre><code>WebElement dynamicElement =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.cssSelector(".dynamic-element")

        )

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    dynamicElement

);</code></pre>

<h2>80. Handling Stale Web Elements</h2>

<p>If the DOM is refreshed or re-rendered, a previously stored WebElement may become stale. Locate the current element again.</p>

<pre><code>WebElement element =

    driver.findElement(By.id("username"));

 

driver.navigate().refresh();

 

element =

    driver.findElement(By.id("username"));</code></pre>

<h2>81. Modify Elements Inside an iframe</h2>

<p>An iframe has its own browsing context. Selenium must switch into the frame before locating and modifying its elements.</p>

<pre><code>WebElement frame =

    driver.findElement(By.id("paymentFrame"));

 

driver.switchTo().frame(frame);

 

WebElement payButton =

    driver.findElement(By.id("pay"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    payButton

);

 

driver.switchTo().defaultContent();</code></pre>

<h2>82. Modify Elements Inside a Modal</h2>

<pre><code>WebElement modalInput =

    driver.findElement(

        By.cssSelector(".modal input")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    modalInput

);</code></pre>

<h2>83. Modify Login Form Elements</h2>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));

 

WebElement password =

    driver.findElement(By.id("password"));

 

username.clear();

username.sendKeys("admin");

 

password.clear();

password.sendKeys("Password123");</code></pre>

<h2>84. Modify Login Button Style</h2>

<pre><code>WebElement loginButton =

    driver.findElement(By.id("login"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid green';",

    loginButton

);</code></pre>

<h2>85. Modify an E-Commerce Product Card</h2>

<pre><code>WebElement product =

    driver.findElement(

        By.cssSelector(".product-card")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    product

);</code></pre>

<h2>86. Modify Checkout Form</h2>

<pre><code>WebElement address =

    driver.findElement(By.id("address"));

 

address.clear();

address.sendKeys("Mumbai, India");</code></pre>

<h2>87. Modify Navigation Link</h2>

<pre><code>WebElement home =

    driver.findElement(By.linkText("Home"));

 

js.executeScript(

    "arguments[0].style.color='red';",

    home

);</code></pre>

<h2>88. Modify Form Button Text</h2>

<pre><code>WebElement submit =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].textContent='Submit Form';",

    submit

);</code></pre>

<h2>89. Modify Web Elements with Page Object Model</h2>

<p>When element modification is used across multiple test cases, it can be organized into reusable Page Object or utility methods. This helps keep test code maintainable.</p>

<pre><code>public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public WebElement getUsername() {

        return driver.findElement(username);

    }

 

    public WebElement getPassword() {

        return driver.findElement(password);

    }

}</code></pre>

<h2>90. Using Page Object Elements</h2>

<pre><code>LoginPage loginPage =

    new LoginPage(driver);

 

WebElement username =

    loginPage.getUsername();

 

highlight(driver, username);</code></pre>

<h2>91. Complete Modification Utility Class</h2>

<pre><code>public class ModifyElementUtils {

 

    public static void highlight(

            WebDriver driver,

            WebElement element) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            element

        );

    }

 

    public static void setAttribute(

            WebDriver driver,

            WebElement element,

            String attribute,

            String value) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].setAttribute(" +

            "arguments[1], arguments[2]);",

            element,

            attribute,

            value

        );

    }

 

    public static void removeAttribute(

            WebDriver driver,

            WebElement element,

            String attribute) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].removeAttribute(arguments[1]);",

            element,

            attribute

        );

    }

 

    public static void setStyle(

            WebDriver driver,

            WebElement element,

            String property,

            String value) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style[arguments[1]]=arguments[2];",

            element,

            property,

            value

        );

    }

}</code></pre>

<h2>92. Using the Complete Utility</h2>

<pre><code>ModifyElementUtils.highlight(

    driver,

    username

);

 

ModifyElementUtils.setAttribute(

    driver,

    username,

    "placeholder",

    "Enter Username"

);

 

ModifyElementUtils.setStyle(

    driver,

    username,

    "backgroundColor",

    "yellow"

);</code></pre>

<h2>93. Modify Web Elements and Perform Normal Selenium Action</h2>

<p>Modification and interaction are separate concepts. For example, JavaScript can highlight an element while Selenium performs the actual click.</p>

<pre><code>WebElement button =

    driver.findElement(By.id("submit"));

 

ModifyElementUtils.highlight(

    driver,

    button

);

 

button.click();</code></pre>

<h2>94. Selenium Click vs JavaScript Modification</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Requirement</th><th>Recommended Technique</th></tr>

<tr><td>Normal click</td><td>WebElement.click()</td></tr>

<tr><td>Enter text</td><td>sendKeys()</td></tr>

<tr><td>Clear text</td><td>clear()</td></tr>

<tr><td>Read attribute</td><td>getAttribute()</td></tr>

<tr><td>Modify attribute</td><td>JavaScript setAttribute()</td></tr>

<tr><td>Remove attribute</td><td>JavaScript removeAttribute()</td></tr>

<tr><td>Modify CSS</td><td>JavaScript style properties</td></tr>

<tr><td>Modify DOM text</td><td>textContent/innerText</td></tr>

<tr><td>Advanced mouse interaction</td><td>Actions class</td></tr>

</table>

<h2>95. Why Not Use JavaScript for Everything?</h2>

<p>JavaScriptExecutor is powerful, but using it for every interaction can make tests less representative of normal user behavior. Selenium's standard WebDriver APIs should generally be preferred for regular browser interactions.</p>

<h2>96. Common Mistake: Modifying Without Waiting</h2>

<p>If the element has not appeared yet, modification may fail.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.presenceOfElementLocated(

            By.id("username")

        )

    );</code></pre>

<h2>97. Common Mistake: Using an Old WebElement</h2>

<p>After a page refresh or DOM re-render, a previously stored WebElement may become stale. Re-locate the element when necessary.</p>

<h2>98. Common Mistake: Ignoring Application Events</h2>

<p>Directly changing a DOM value does not necessarily trigger the events used by the application. When appropriate, dispatch the required event and verify the resulting application state.</p>

<h2>99. Common Mistake: Bypassing Application Behavior</h2>

<p>Removing disabled attributes or forcing hidden elements to become visible can bypass normal application behavior. Such techniques should only be used when they match the specific testing objective.</p>

<h2>100. Common Mistake: Changing Locator Attributes</h2>

<p>Changing an id, class, or name during automation can cause later locators to fail and can make test behavior difficult to understand.</p>

<h2>101. Best Practice: Prefer WebDriver APIs</h2>

<ul>

<li>Use click() for normal clicks.</li>

<li>Use sendKeys() for normal keyboard input.</li>

<li>Use clear() for editable fields.</li>

<li>Use Select for standard HTML select controls.</li>

<li>Use Actions for advanced mouse and keyboard interactions.</li>

<li>Use JavaScriptExecutor for appropriate DOM-level tasks.</li>

</ul>

<h2>102. Best Practice: Use Explicit Waits</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("username")

        )

    );</code></pre>

<h2>103. Best Practice: Verify Modification</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);

 

String status =

    element.getAttribute("data-status");

 

System.out.println(

    "Status: " + status

);</code></pre>

<h2>104. Best Practice: Restore Temporary Changes</h2>

<p>Temporary CSS or DOM changes should be restored when they are used only for debugging, visualization, or screenshots.</p>

<h2>105. Best Practice: Create Reusable Utilities</h2>

<p>If the same modification is needed across several tests, create reusable utility methods rather than repeating JavaScript throughout the test suite.</p>

<h2>106. Best Practice: Keep JavaScript Small</h2>

<p>Short JavaScript statements are easier to understand, debug, and maintain than large blocks of embedded JavaScript.</p>

<h2>107. Practical Example: Login Page Modification</h2>

<pre><code>WebDriver driver = new ChromeDriver();

 

driver.manage().window().maximize();

driver.get("https://example.com/login");

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

WebElement username =

    driver.findElement(By.id("username"));

 

WebElement password =

    driver.findElement(By.id("password"));

 

WebElement login =

    driver.findElement(By.id("login"));

 

username.clear();

username.sendKeys("admin");

 

password.clear();

password.sendKeys("Password123");

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    login

);

 

login.click();</code></pre>

<h2>108. Practical Example: Modify Multiple Form Fields</h2>

<pre><code>WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement email =

    driver.findElement(By.id("email"));

 

WebElement phone =

    driver.findElement(By.id("phone"));

 

firstName.clear();

firstName.sendKeys("John");

 

email.clear();

email.sendKeys("[email protected]");

 

phone.clear();

phone.sendKeys("9876543210");</code></pre>

<h2>109. Practical Example: Modify Button Text and Style</h2>

<pre><code>WebElement button =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].textContent='Submit Application';" +

    "arguments[0].style.backgroundColor='green';" +

    "arguments[0].style.color='white';",

    button

);</code></pre>

<h2>110. Practical Example: Modify All Input Fields</h2>

<pre><code>List&lt;WebElement&gt; inputs =

    driver.findElements(By.cssSelector("input"));

 

for (WebElement input : inputs) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        input

    );

}</code></pre>

<h2>111. Practical Example: Modify Product Cards</h2>

<pre><code>List&lt;WebElement&gt; products =

    driver.findElements(

        By.cssSelector(".product-card")

    );

 

for (WebElement product : products) {

    js.executeScript(

        "arguments[0].style.boxShadow='0 0 10px red';",

        product

    );

}</code></pre>

<h2>112. Practical Example: Modify Table Rows</h2>

<pre><code>List&lt;WebElement&gt; rows =

    driver.findElements(

        By.cssSelector("table tbody tr")

    );

 

for (WebElement row : rows) {

    js.executeScript(

        "arguments[0].style.outline='2px solid blue';",

        row

    );

}</code></pre>

<h2>113. Practical Example: Checkbox State</h2>

<pre><code>WebElement terms =

    driver.findElement(By.id("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

System.out.println(

    "Selected: " + terms.isSelected()

);</code></pre>

<h2>114. Practical Example: Controlled JavaScript Checkbox Modification</h2>

<pre><code>js.executeScript(

    "arguments[0].checked=true;" +

    "arguments[0].dispatchEvent(" +

    "new Event('change',{bubbles:true})" +

    ");",

    terms

);</code></pre>

<h2>115. Practical Example: Modify Hidden Element for Debugging</h2>

<pre><code>WebElement hidden =

    driver.findElement(By.id("hiddenElement"));

 

js.executeScript(

    "arguments[0].style.display='block';",

    hidden

);</code></pre>

<h2>116. Practical Example: Remove Disabled State</h2>

<pre><code>WebElement submit =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    submit

);</code></pre>

<h2>117. Practical Example: Add Disabled State</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('disabled','true');",

    submit

);</code></pre>

<h2>118. Practical Example: Modify Link URL</h2>

<pre><code>WebElement profile =

    driver.findElement(By.id("profile"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'href','https://example.com/profile');",

    profile

);</code></pre>

<h2>119. Practical Example: Modify Image Source</h2>

<pre><code>WebElement logo =

    driver.findElement(By.id("logo"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'src','/images/test-logo.png');",

    logo

);</code></pre>

<h2>120. Practical Example: Modify Element Text</h2>

<pre><code>WebElement message =

    driver.findElement(By.id("message"));

 

js.executeScript(

    "arguments[0].textContent='Test completed successfully';",

    message

);</code></pre>

<h2>121. Practical Example: Add CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.add('test-highlight');",

    message

);</code></pre>

<h2>122. Practical Example: Remove CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.remove('test-highlight');",

    message

);</code></pre>

<h2>123. Practical Example: Modify Attribute and Verify</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('data-test','passed');",

    element

);

 

String result =

    element.getAttribute("data-test");

 

if ("passed".equals(result)) {

    System.out.println(

        "Modification successful"

    );

}</code></pre>

<h2>124. Modify Web Elements in TestNG</h2>

<pre><code>import org.testng.annotations.Test;

 

public class ModifyElementTest {

 

    @Test

    public void modifyElementTest() {

 

        WebElement username =

            driver.findElement(By.id("username"));

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            username

        );

 

        username.clear();

        username.sendKeys("admin");

 

        System.out.println(

            username.getAttribute("value")

        );

    }

}</code></pre>

<h2>125. Modify Web Element Flow</h2>

<pre><code>Start

  |

  v

Open Browser

  |

  v

Open Application

  |

  v

Locate Web Element

  |

  v

Wait for Required State

  |

  v

Choose Modification

  |

  +----&gt; WebElement API

  |

  +----&gt; JavaScriptExecutor

  |

  +----&gt; Actions API

  |

  v

Modify Element

  |

  v

Verify Result

  |

  v

Continue Test

  |

  v

End</code></pre>

<h2>126. Web Element Modification Decision Guide</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Requirement</th><th>Recommended Approach</th></tr>

<tr><td>Enter text</td><td>sendKeys()</td></tr>

<tr><td>Clear text</td><td>clear()</td></tr>

<tr><td>Click element</td><td>click()</td></tr>

<tr><td>Read attribute</td><td>getAttribute()</td></tr>

<tr><td>Modify HTML attribute</td><td>JavaScript setAttribute()</td></tr>

<tr><td>Remove attribute</td><td>JavaScript removeAttribute()</td></tr>

<tr><td>Change CSS</td><td>JavaScript style property</td></tr>

<tr><td>Change DOM text</td><td>textContent/innerText</td></tr>

<tr><td>Advanced mouse action</td><td>Actions class</td></tr>

<tr><td>Debug/highlight</td><td>JavaScriptExecutor</td></tr>

</table>

<h2>127. Common Selenium Exceptions</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Possible Reason</th></tr>

<tr><td>NoSuchElementException</td><td>Element cannot be located.</td></tr>

<tr><td>StaleElementReferenceException</td><td>DOM changed after the element was located.</td></tr>

<tr><td>ElementNotInteractableException</td><td>Element cannot be interacted with normally.</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element blocks the click.</td></tr>

<tr><td>TimeoutException</td><td>Expected condition was not met in time.</td></tr>

</table>

<h2>128. Debugging Modification Failures</h2>

<ol>

<li>Verify the locator.</li>

<li>Check whether the element exists.</li>

<li>Check page loading state.</li>

<li>Check whether the element is inside an iframe.</li>

<li>Check whether an overlay or modal is blocking it.</li>

<li>Check for DOM re-rendering.</li>

<li>Re-locate stale elements.</li>

<li>Use explicit waits.</li>

<li>Inspect the element using browser developer tools.</li>

<li>Verify the modified value or attribute.</li>

</ol>

<h2>129. Interview Question: What is Modify Web Elements?</h2>

<p>Modify Web Elements means changing or controlling attributes, properties, styles, text, or state of web elements during automation. Selenium's WebElement API is normally used for standard interactions, while JavaScriptExecutor can perform appropriate DOM-level modifications.</p>

<h2>130. Interview Question: Can Selenium Modify HTML Attributes?</h2>

<p>JavaScriptExecutor can directly modify HTML attributes using JavaScript methods such as setAttribute() and removeAttribute().</p>

<h2>131. Interview Question: How Do You Modify an Attribute?</h2>

<pre><code>js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);</code></pre>

<h2>132. Interview Question: How Do You Change CSS?</h2>

<pre><code>js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    element

);</code></pre>

<h2>133. Interview Question: How Do You Modify Text?</h2>

<pre><code>js.executeScript(

    "arguments[0].textContent='Updated Text';",

    element

);</code></pre>

<h2>134. Interview Question: What is arguments[0]?</h2>

<p>arguments[0] is the first parameter supplied to executeScript(). When a WebElement is passed, it represents that element's corresponding DOM object inside the JavaScript execution context.</p>

<h2>135. Interview Question: Can JavaScript Remove Disabled State?</h2>

<p>Yes. JavaScript can remove a disabled attribute, but this can bypass the application's intended state. It should only be used when that behavior is part of the specific test objective.</p>

<h2>136. Interview Question: Does JavaScript Value Modification Trigger Events?</h2>

<p>Not necessarily. Direct DOM property modification may not reproduce the events generated by normal user interaction. An appropriate event can be dispatched when the test specifically requires it.</p>

<h2>137. Interview Question: Should JavaScriptExecutor Replace Selenium Methods?</h2>

<p>No. Selenium's standard APIs should generally be preferred for normal browser interactions. JavaScriptExecutor should be used for suitable DOM-level operations, debugging, or controlled specialized scenarios.</p>

<h2>138. Interview Question: How Do You Highlight an Element?</h2>

<pre><code>js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);</code></pre>

<h2>139. Interview Question: How Do You Remove an Attribute?</h2>

<pre><code>js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    element

);</code></pre>

<h2>140. Interview Question: How Do You Modify Multiple Elements?</h2>

<pre><code>List&lt;WebElement&gt; elements =

    driver.findElements(

        By.cssSelector(".item")

    );

 

for (WebElement element : elements) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        element

    );

}</code></pre>

<h2>141. Quick Revision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Concept</th><th>Key Point</th></tr>

<tr><td>WebElement</td><td>Represents an HTML element.</td></tr>

<tr><td>sendKeys()</td><td>Enters keyboard input.</td></tr>

<tr><td>clear()</td><td>Clears editable fields.</td></tr>

<tr><td>getAttribute()</td><td>Reads an attribute or property value.</td></tr>

<tr><td>setAttribute()</td><td>Modifies an HTML attribute.</td></tr>

<tr><td>removeAttribute()</td><td>Removes an HTML attribute.</td></tr>

<tr><td>style</td><td>Modifies CSS properties.</td></tr>

<tr><td>classList</td><td>Adds, removes, or toggles CSS classes.</td></tr>

<tr><td>textContent</td><td>Reads or modifies DOM text.</td></tr>

<tr><td>JavascriptExecutor</td><td>Executes JavaScript in the browser context.</td></tr>

<tr><td>Explicit Wait</td><td>Synchronizes automation with dynamic elements.</td></tr>

<tr><td>POM</td><td>Organizes reusable page element logic.</td></tr>

</table>

<h2>142. Best Practices Checklist</h2>

<ul>

<li>Use stable locators.</li>

<li>Prefer normal Selenium methods for normal user interactions.</li>

<li>Use JavaScriptExecutor only when appropriate.</li>

<li>Use explicit waits for dynamic elements.</li>

<li>Re-locate elements after DOM refreshes or re-rendering.</li>

<li>Verify important modifications.</li>

<li>Consider application-specific events when changing DOM properties.</li>

<li>Keep JavaScript readable and focused.</li>

<li>Create reusable utility methods.</li>

<li>Restore temporary changes when necessary.</li>

<li>Use controlled test environments.</li>

<li>Do not use DOM modification to hide actual application defects.</li>

</ul>

<h2>143. Practical Mini Project: Web Element Modification Test Suite</h2>

<p>A practical Selenium project can combine login automation, form modification, attribute verification, CSS highlighting, checkbox state validation, dynamic elements, and debugging.</p>

<pre><code>Login Page

   |

   v

Locate Username

   |

   v

Enter Username

   |

   v

Locate Password

   |

   v

Enter Password

   |

   v

Highlight Login Button

   |

   v

Verify Element

   |

   v

Click Login

   |

   v

Verify Dashboard

   |

   v

End Test</code></pre>

<h2>144. Complete Practical Example</h2>

<pre><code>WebDriver driver = new ChromeDriver();

 

driver.manage().window().maximize();

 

driver.get("https://example.com");

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

WebElement username =

    driver.findElement(By.id("username"));

 

WebElement login =

    driver.findElement(By.id("login"));

 

username.clear();

username.sendKeys("admin");

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'data-test-status','prepared');",

    username

);

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    login

);

 

String status =

    username.getAttribute("data-test-status");

 

System.out.println(

    "Status: " + status

);

 

login.click();

 

driver.quit();</code></pre>

<h2>145. Conclusion</h2>

<p>Modify Web Elements is an important Selenium WebDriver concept for understanding how automated tests can inspect and change elements in the browser DOM. Selenium's WebElement methods should normally be used for standard interactions such as typing, clicking, clearing fields, and selecting controls.</p>

<p>JavaScriptExecutor provides additional capabilities for controlled DOM operations such as changing attributes, CSS styles, text, classes, and certain element properties. The most reliable automation approach combines stable locators, appropriate waits, normal Selenium interactions, reusable utilities, and verification of the resulting application state.</p>

<hr>

<h2>146. Selenium Training Resources</h2>

<p>JustAcademy's Selenium training curriculum includes Selenium WebDriver, locating elements, browser automation, forms, buttons, dropdowns, WebElements, advanced interactions, waits, dynamic elements, TestNG, Page Object Model, automation frameworks, reporting, debugging, and practical automation projects.</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a></p>

<p><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<h2>147. Final Quick Reference</h2>

<pre><code>// Locate

WebElement element =

    driver.findElement(By.id("username"));

 

// Enter value

element.clear();

element.sendKeys("Admin");

 

// Read attribute

String value =

    element.getAttribute("value");

 

// JavaScript

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

// Modify attribute

js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);

 

// Remove attribute

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    element

);

 

// Modify CSS

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

 

// Modify text

js.executeScript(

    "arguments[0].textContent='Updated';",

    element

);

 

// Add class

js.executeScript(

    "arguments[0].classList.add('active');",

    element

);

 

// Remove class

js.executeScript(

    "arguments[0].classList.remove('active');",

    element

);</code></pre>

</div>

Previous Next
whatsapp